package com.hzchendou.blog.demo.common.model.vo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hzchendou.blog.demo.common.enums.ResultCodeEnums;
import com.hzchendou.blog.demo.common.utils.JacksonUtils;
import lombok.Data;

/**
 * 结果集模型
 *
 * @Date: 2022-05-23 11:19
 * @since: 1.0
 */
@Data
public class ResultVO<T> {

    private int code;
    private T data;
    private String message;

    private ResultVO(int code, T data, String message) {
        this.code = code;
        this.data = data;
        this.message = message;
    }

    private ResultVO(ResultCodeEnums resultCode) {
        this.code = resultCode.getCode();
        this.message = resultCode.getMessage();
    }

    public static ResultVO fail(ResultCodeEnums resultCode) {
        return new ResultVO(resultCode);
    }

    public static ResultVO fail(String message) {
        return new ResultVO(ResultCodeEnums.FAIL.getCode(), null, message);
    }


    public static <T> ResultVO success(T data) {
        return new ResultVO(ResultCodeEnums.SUCCESS.getCode(), data, null);
    }

    /**
     * 转化为JSON
     *
     * @return
     */
    public String toJson() throws JsonProcessingException {
        return JacksonUtils.toJSON(this);
    }

}
